
package org.TCC_NOVO.client.visual;

import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.Ext;
import com.gwtext.client.core.Function;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.IntegerFieldDef;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.util.Format;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.Tool;
import com.gwtext.client.widgets.Toolbar;
import com.gwtext.client.widgets.ToolbarButton;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.grid.CellMetadata;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.Renderer;
import com.gwtext.client.widgets.grid.event.GridCellListenerAdapter;
import java.util.ArrayList;
import java.util.List;

import org.TCC_NOVO.client.GWTServiceAsync;
import org.TCC_NOVO.client.modelo.Projeto;
import org.TCC_NOVO.client.modelo.Usuario;

public class ProjetosPanel extends Panel{

    private final GWTServiceAsync controller;
    private String IDF_Usuario;
    private String sPapel = "";

    private ProjetosForm ProjForm;
    public int ID_ProjAtual = 0;
    public MatrizPanelWindow matPanelWin;

    private Store store;
    private GridPanel grid;
    private RecordDef recordDef;
    private Toolbar toolbar;
    private ArrayList<Projeto> ArrayProjeto = new ArrayList();
    private List<Usuario> usuarios = new ArrayList();
    private ProjetosPanel self;

    public List<Usuario> getUsuarios() {
        return usuarios;
    }

    public ProjetosPanel(GWTServiceAsync controller, String IDF_usua, String papel) {
        this.controller = controller;
        this.IDF_Usuario = IDF_usua;
        this.sPapel = papel;
        this.self = this;
        this.init();
    }

    private void CarregarDados(ArrayList<Projeto> result){
        ArrayProjeto = result;
        for (int i = 0; i < result.size(); ++i) {
            addRecord(result.get(i));
        }
    }

     private void init(){
        this.setBorder(true);
        this.setPaddings(2);

        controller.retornarDadosUsuarios("Professor Conteudista", new CallBackRetUsuarios());

        recordDef = new RecordDef(new FieldDef[]{
            new IntegerFieldDef("ID"),
            new StringFieldDef("Nome"),
            new StringFieldDef("Assunto"),
            new StringFieldDef("usuario"),
            new StringFieldDef("DataInicio"),
            new StringFieldDef("DataEntrega"),
            new StringFieldDef("Observacoes"),
            new StringFieldDef("Conteudista"),
        });

        store = new Store(recordDef);
        grid = new GridPanel();
        grid.setStore(store);

        ColumnConfig configClique = new ColumnConfig("Matriz","idcoluna");
        Renderer btCliqueRenderer = new Renderer() {
            @Override
            public String render(Object value, CellMetadata cellMetadata, final Record record, int rowIndex, int colNum, Store stores) {
                final Button btn = new Button("Matriz DI", new ButtonListenerAdapter() {
                    @Override
                    public void onClick(Button button, EventObject e) {                        

                        grid.getSelectionModel().selectRow(Integer.parseInt(button.getTitle()));

                        if (grid.getSelectionModel().getSelected() == null){
                            MessageBox.alert("Necessário Selecionar Algum Registro! ");
                        }else {
                            if (ID_ProjAtual > 0)
                                matPanelWin = new MatrizPanelWindow(controller, ID_ProjAtual, Integer.parseInt(IDF_Usuario));
                            else
                                matPanelWin = new MatrizPanelWindow(controller, grid.getSelectionModel().getSelected().getAsInteger("ID"), Integer.parseInt(IDF_Usuario));

                          ID_ProjAtual = 0;
                          matPanelWin.show();
                        }
                        grid.getSelectionModel().deselectRow(Integer.parseInt(button.getTitle()));
                    }
                });
                final String id = Ext.generateId();
                btn.setRenderToID(id);
                btn.setTitle(Integer.toString(rowIndex));
                btn.setIcon("Images/matriz.png");
                DeferredCommand.addCommand(new Command() {
                    @Override
                    public void execute() {
                        if (DOM.getElementById(id) != null)
                            btn.render(id);
                    }
                });
                return Format.format("<div id='{0}' class='fixGridButton' style='padding:0px;width:100%;height:18px;'></div>", id);
            }
        };
        configClique.setRenderer(btCliqueRenderer);
        //grid.setColumnModel(new ColumnModel(new ColumnConfig[] {configClique }));

        ColumnConfig[] columns = new ColumnConfig[]{
            new ColumnConfig("Nome", "Nome", 190, true),
            new ColumnConfig("Assunto", "Assunto", 190, true),
            new ColumnConfig("Conteudista Responsável", "Conteudista", 160, true),
            new ColumnConfig("Data Inicio", "DataInicio", 120, true),
            new ColumnConfig("Data Prazo Entrega", "DataEntrega", 120, true),
            configClique,
        };

        ColumnModel columnModel = new ColumnModel(columns);
        grid.setColumnModel(columnModel);
        grid.setFrame(true);
        grid.setStripeRows(true);
        grid.setSize(1020, 600);
        grid.setTitle("Projetos");
        grid.addTool(new Tool(Tool.REFRESH, new Function() {
            @Override
            public void execute() {
                grid.getEl().mask("Carregando", "x-mask-loading");
                CarregarGrid();
                Timer timer = new Timer() {
                    @Override
                    public void run() {
                        grid.getEl().unmask();
                    }
                };
                timer.schedule(1000);
            }
        }, "Atualizar"));

        grid.addGridCellListener(new GridCellListenerAdapter(){
            @Override
            public void onCellDblClick(GridPanel grid, int rowIndex, int colIndex, EventObject e){
                ProjForm.ID_Form = grid.getSelectionModel().getSelected().getId();
                ProjForm.show(true);
                ProjForm.loadRecord(grid.getSelectionModel().getSelected());
            }
        });

        if (sPapel.equals("Coordenador")){
            toolbar = getToolbar();
            toolbar.setSize(grid.getWidth(), 30);
            this.add(toolbar);
        }
        this.add(grid);

        CarregarGrid();
     }

     public void CarregarGrid(){
         store.removeAll();
         String sSQL = "select A.*, B.Nick Nick_Usuario, C.Nick Nick_Conteud " +
                       "from projeto A " +
                       "inner join Usuario B on B.ID = A.IDF_Usuario " +
                       "left join Usuario C on C.ID = A.IDF_Conteudista " +
                       "where A.IDF_Usuario = "+IDF_Usuario + " or A.IDF_Conteudista = "+IDF_Usuario;
         controller.RetornarDadosProjeto(sSQL, new CallBackRetProjetos());
     }

     private class CallBackRetProjetos implements AsyncCallback<ArrayList<Projeto>> {
        @Override
	public void onFailure(Throwable e) {
		MessageBox.alert("Erro ao carregar dados... ", e.getMessage());
	}
        @Override
	public void onSuccess(ArrayList<Projeto> result) {
                CarregarDados(result);
        }
     }

     private class CallBackRetUsuarios implements AsyncCallback<List<Usuario>> {
        @Override
	public void onFailure(Throwable e) {
            MessageBox.alert("Erro ao carregar dados... ", e.getMessage());
	}
        @Override
	public void onSuccess(List<Usuario> result) {
            usuarios = result;
            ProjForm = new ProjetosForm(self, controller, Integer.parseInt(IDF_Usuario));
        }
    }

     private void removeProjetos(){
        store.remove(grid.getSelectionModel().getSelected());
    }

     public void addRecord(Projeto Proj){
        Object[] rowData = new Object[]{
          Proj.getID(),
          Proj.getNome(),
          Proj.getAssunto(),
          Proj.getUsuarioResp(),
          Proj.getDataIni().toString(),
          Proj.getDataEnt().toString(),
          Proj.getObserv(),
          Proj.getConteudista(),
        };
        Record record = recordDef.createRecord(rowData[0].toString(), rowData);
        store.add(record);
    }

     public Toolbar getToolbar(){

         final AsyncCallback callbackExcluirReg = new AsyncCallback() {
            @Override
            public void onSuccess(Object result) {
                //MessageBox.alert("Registro Gravado com Sucesso!");
            }
            @Override
            public void onFailure(Throwable caught) {
               MessageBox.alert("Erro ", caught.getMessage()); }
        };

        Toolbar toobar = new Toolbar();

        if (sPapel.equals("Coordenador")){
            ToolbarButton btnNovo = new ToolbarButton();
            btnNovo.setText(" Incluir");
            btnNovo.setIcon("Images/filenew.png");
            btnNovo.setTooltip("Incluir um novo registro");
            btnNovo.addListener(new ButtonListenerAdapter(){
                @Override
                public void onClick(Button button, EventObject e){
                    ProjForm.show(false);
                    Object[] rowData = new Object[]{"","","","","",""};
                    Record record = recordDef.createRecord(rowData[0].toString(), rowData);
                    ProjForm.loadRecord(record);
                }
            });
            toobar.addButton(btnNovo);
        }        

        if (sPapel.equals("Coordenador")){
            ToolbarButton btnEdit = new ToolbarButton();
            btnEdit.setText(" Editar");
            btnEdit.setIcon("Images/edit.png");
            btnEdit.setTooltip("Edita o registro selecionado");
            btnEdit.addListener(new ButtonListenerAdapter(){
                @Override
                public void onClick(Button button, EventObject e){
                    if (grid.getSelectionModel().getSelected() == null){
                        MessageBox.alert("Necessário Selecionar Algum Registro! ");
                    }else{
                        ProjForm.ID_Form = grid.getSelectionModel().getSelected().getId();
                        ProjForm.show(true);
                        ProjForm.loadRecord(grid.getSelectionModel().getSelected());
                    }
                }
            });
            toobar.addButton(btnEdit);
        }        

        if (sPapel.equals("Coordenador")){
            ToolbarButton btnRemove = new ToolbarButton();
            btnRemove.setText(" Remover");
            btnRemove.setIcon("Images/remove.png");
            btnRemove.setTooltip("Remove o registro selecionado");
            btnRemove.addListener(new ButtonListenerAdapter(){
                @Override
                public void onClick(Button button, EventObject e){
                    if (grid.getSelectionModel().getSelected() == null){
                        MessageBox.alert("Necessário Selecionar Algum Registro! ");
                    }else {
                        MessageBox.confirm("Confirmação de Exclusão", "Deseja Realmente Excluir o Registro?", new MessageBox.ConfirmCallback(){
                            @Override
                        public void execute(String btnID){
                            if (btnID.equals("yes")){
                                //Remoção do Registro no Servidor (Banco de Dados)...
                                String sSQL = "Delete from Projeto where ID = '"+grid.getSelectionModel().getSelected().getAsString("ID")+"'";
                                controller.ExcluirRegistro(sSQL, callbackExcluirReg);
                                //Remoção do Registro no Cliente (Grid)...
                                removeProjetos();
                            }
                        }});
                    }
                }
            });
            toobar.addButton(btnRemove);
        }
     
        return toobar;
    }

}
